<template>
  <div class="admin-homepage">
    <div class="page-header">
      <h2>首页内容管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleSaveAll">
          <el-icon><Check /></el-icon>
          保存所有更改
        </el-button>
        <el-button @click="handlePreview">
          <el-icon><View /></el-icon>
          预览效果
        </el-button>
      </div>
    </div>

    <!-- 内容管理标签页 -->
    <el-tabs v-model="activeTab" type="border-card" class="content-tabs">
      <!-- 轮播图管理 -->
      <el-tab-pane label="轮播图管理" name="carousel">
        <div class="tab-content">
          <div class="section-header">
            <h3>轮播图设置</h3>
            <el-button type="primary" size="small" @click="addCarouselItem">
              <el-icon><Plus /></el-icon>
              添加轮播图
            </el-button>
          </div>

          <el-table :data="carouselData" border stripe>
            <el-table-column prop="title" label="标题" width="200" />
            <!-- <el-table-column prop="subtitle" label="副标题" width="200" /> -->
            <el-table-column prop="description" label="描述" width="250" />
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.image"
                  fit="cover"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.image)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="buttonText" label="按钮文字" width="120" />
            <el-table-column prop="action" label="跳转动作" width="120" />
            <el-table-column
              prop="link"
              label="跳转链接"
              width="150"
              show-overflow-tooltip
            />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editCarouselItem(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteCarouselItem($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleCarouselStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展商评价管理 -->
      <el-tab-pane label="展商评价" name="testimonials">
        <div class="tab-content">
          <div class="section-header">
            <h3>展商评价设置</h3>
            <el-button type="primary" size="small" @click="addTestimonial">
              <el-icon><Plus /></el-icon>
              添加评价
            </el-button>
          </div>
          <el-table :data="testimonialsData" border stripe>
            <el-table-column prop="company" label="企业名称" width="200" />
            <el-table-column prop="content" label="评价内容" width="400" />
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.image"
                  fit="cover"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.image)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">{{
                  row.status === "active" ? "启用" : "禁用"
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editTestimonial(row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteTestimonial($index)"
                    >删除</el-button
                  >
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleTestimonialStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展会主视觉管理 -->
      <el-tab-pane label="展会主视觉" name="mainVisual" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会主视觉设置</h3>
          </div>

          <el-form :model="mainVisualData" label-width="120px">
            <el-form-item label="展会主标题">
              <el-input
                v-model="mainVisualData.title"
                placeholder="请输入展会主标题"
              />
            </el-form-item>

            <el-form-item label="展会副标题">
              <el-input
                v-model="mainVisualData.subtitle"
                placeholder="请输入展会副标题"
              />
            </el-form-item>

            <el-form-item label="主视觉图片">
              <div class="image-upload-container">
                <el-upload
                  class="image-uploader"
                  :action="uploadAction"
                  :headers="uploadHeaders"
                  :data="{ type: 'mainVisual' }"
                  :show-file-list="false"
                  :on-success="
                    (response) => handleImageSuccess(response, 'mainVisual')
                  "
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                >
                  <img
                    v-if="mainVisualData.image"
                    :src="mainVisualData.image"
                    class="uploaded-image"
                  />
                  <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-input
                  v-model="mainVisualData.image"
                  placeholder="或直接输入图片URL"
                  style="margin-top: 10px"
                />
              </div>
            </el-form-item>

            <el-form-item label="统计数据">
              <div class="stats-container">
                <div
                  class="stat-item"
                  v-for="(stat, index) in mainVisualData.stats"
                  :key="index"
                >
                  <el-input v-model="stat.value" placeholder="数值" />
                  <el-input v-model="stat.label" placeholder="标签" />
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeVisualStat(index)"
                    >删除</el-button
                  >
                </div>
                <el-button type="primary" size="small" @click="addVisualStat"
                  >添加统计项</el-button
                >
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveMainVisual"
                >保存主视觉设置</el-button
              >
              <el-button @click="resetMainVisual">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 展会概览管理 -->
      <el-tab-pane label="展会概览" name="overview">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会概览设置</h3>
          </div>

          <el-form :model="overviewData" label-width="120px">
            <div class="statistics-grid">
              <el-card
                v-for="(stat, index) in overviewData.items"
                :key="index"
                class="stat-card"
              >
                <div class="stat-header">
                  <h4>统计项 {{ index + 1 }}</h4>
                  <div class="stat-actions">
                    <el-button
                      type="primary"
                      link
                      @click="editOverviewItem(index)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="deleteOverviewItem(index)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                <el-form-item label="标题">
                  <el-input v-model="stat.title" placeholder="例如：展会面积" />
                </el-form-item>
                <el-form-item label="数值">
                  <el-input v-model="stat.value" placeholder="例如：15000m²" />
                </el-form-item>
                <el-form-item label="排序">
                  <el-input-number v-model="stat.sort" :min="1" />
                </el-form-item>
              </el-card>
            </div>
            <div class="add-stat-button">
              <el-button type="primary" @click="addOverviewItem">
                <el-icon><Plus /></el-icon>
                添加统计项
              </el-button>
            </div>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 重点活动管理 -->
      <el-tab-pane label="重点活动" name="events" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>重点活动设置</h3>
            <el-button type="primary" size="small" @click="addEvent">
              <el-icon><Plus /></el-icon>
              添加活动
            </el-button>
          </div>

          <el-table :data="eventsData" border stripe>
            <el-table-column prop="title" label="活动标题" width="200" />
            <el-table-column prop="description" label="活动描述" width="300" />
            <el-table-column label="活动图片" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.image"
                  fit="cover"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.image)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="buttonText" label="按钮文字" width="120" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editEvent(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteEvent($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleEventStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 参展企业轮播管理 -->
      <el-tab-pane label="参展企业轮播" name="exhibitors">
        <div class="tab-content">
          <div class="section-header">
            <h3>参展企业轮播设置</h3>
            <div class="header-actions">
              <el-button
                type="success"
                size="small"
                @click="downloadExhibitorTemplate"
              >
                <el-icon><Download /></el-icon>
                下载模板
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="triggerExhibitorImport"
              >
                <el-icon><Upload /></el-icon>
                批量导入
              </el-button>
              <el-button type="primary" size="small" @click="addExhibitor">
                <el-icon><Plus /></el-icon>
                添加企业
              </el-button>
            </div>
          </div>

          <!-- 隐藏的文件上传输入框 -->
          <input
            ref="exhibitorImportRef"
            type="file"
            accept=".csv,.xlsx,.xls"
            style="display: none"
            @change="handleExhibitorImport"
          />

          <el-table :data="exhibitorsData" border stripe>
            <el-table-column prop="name" label="企业名称" width="150" />
            <el-table-column label="企业Logo" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.logo"
                  fit="contain"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.logo)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="group" label="分组" width="100" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editExhibitor(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteExhibitor($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleExhibitorStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展会协助管理 -->
      <el-tab-pane label="展会协助" name="assistance" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会协助设置</h3>
            <el-button type="primary" size="small" @click="addAssistance">
              <el-icon><Plus /></el-icon>
              添加协助项
            </el-button>
          </div>

          <el-table :data="assistanceData" border stripe>
            <el-table-column prop="title" label="标题" width="150" />
            <el-table-column prop="description" label="描述" width="250" />
            <el-table-column prop="icon" label="图标" width="100" />
            <el-table-column prop="link" label="跳转链接" width="150" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editAssistance(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteAssistance($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleAssistanceStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展会图片轮播管理 -->
      <el-tab-pane label="展会图片轮播" name="gallery" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会图片轮播设置</h3>
            <el-button type="primary" size="small" @click="addGalleryImage">
              <el-icon><Plus /></el-icon>
              添加图片
            </el-button>
          </div>

          <el-table :data="galleryData" border stripe>
            <el-table-column prop="title" label="图片标题" width="150" />
            <el-table-column prop="description" label="图片描述" width="250" />
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.url"
                  fit="cover"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.url)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editGalleryImage(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteGalleryImage($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleGalleryStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展会现场直播管理 -->
      <el-tab-pane label="展会现场直播" name="live">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会现场直播设置</h3>
            <el-button type="primary" size="small" @click="addLiveImage">
              <el-icon><Plus /></el-icon>
              添加直播图片
            </el-button>
          </div>

          <!-- 查询条件 -->
          <el-form
            :model="liveQueryForm"
            label-width="120px"
            class="query-form"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="直播标题">
                  <el-input
                    v-model="liveQueryForm.title"
                    placeholder="请输入直播标题"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="直播状态">
                  <el-select
                    v-model="liveQueryForm.status"
                    placeholder="请选择状态"
                    clearable
                  >
                    <el-option label="直播中" value="LIVE" />
                    <el-option label="即将开始" value="即将开始" />
                    <el-option label="已结束" value="已结束" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="观看人数">
                  <el-input
                    v-model="liveQueryForm.viewers"
                    placeholder="请输入观看人数"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" @click="searchLiveData"
                    >查询</el-button
                  >
                  <el-button @click="resetLiveQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 直播图片列表 -->
          <div class="live-images-section">
            <h4>直播图片管理</h4>
            <el-table :data="filteredLiveImages" border stripe>
              <el-table-column label="预览" width="120">
                <template #default="{ row }">
                  <el-image
                    :src="row.url"
                    fit="cover"
                    style="
                      width: 80px;
                      height: 60px;
                      border-radius: 4px;
                      cursor: pointer;
                    "
                    @click="previewImage(row.url)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题" width="200" />
              <el-table-column prop="description" label="描述" width="300" />
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                    {{ row.status === "active" ? "启用" : "禁用" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row, $index }">
                  <div class="action-buttons">
                    <el-button size="small" @click="editLiveImage(row, $index)">
                      编辑
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="deleteLiveImage($index)"
                    >
                      删除
                    </el-button>
                    <el-button
                      size="small"
                      :type="row.status === 'active' ? 'warning' : 'success'"
                      @click="toggleLiveImageStatus(row)"
                    >
                      {{ row.status === "active" ? "禁用" : "启用" }}
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>

      <!-- 宣传视频管理 -->
      <el-tab-pane label="宣传视频" name="video">
        <div class="tab-content">
          <div class="section-header">
            <h3>宣传视频设置</h3>
          </div>

          <el-form :model="videoData" label-width="120px">
            <el-form-item label="视频标题">
              <el-input
                v-model="videoData.title"
                placeholder="请输入视频标题"
              />
            </el-form-item>

            <el-form-item label="视频副标题">
              <el-input
                v-model="videoData.subtitle"
                placeholder="请输入视频副标题"
              />
            </el-form-item>

            <el-form-item label="视频文件">
              <div class="video-upload-container">
                <el-upload
                  class="video-uploader"
                  :action="videoUploadAction"
                  :headers="uploadHeaders"
                  :data="{ type: 'video' }"
                  :show-file-list="false"
                  :on-success="(response) => handleVideoSuccess(response)"
                  :before-upload="beforeVideoUpload"
                  accept="video/*"
                >
                  <el-button type="primary" :loading="videoUploading">
                    <el-icon><Upload /></el-icon>
                    {{ videoUploading ? "上传中..." : "选择视频文件" }}
                  </el-button>
                </el-upload>
                <div v-if="videoData.videoUrl" class="video-preview">
                  <video
                    :src="videoData.videoUrl"
                    controls
                    style="width: 300px; height: 200px; margin-top: 10px"
                  ></video>
                </div>
                <el-input
                  v-model="videoData.videoUrl"
                  placeholder="或直接输入视频链接"
                  style="margin-top: 10px"
                />
              </div>
            </el-form-item>

            <el-form-item label="封面图片">
              <div class="image-upload-container">
                <el-upload
                  class="image-uploader"
                  :action="uploadAction"
                  :headers="uploadHeaders"
                  :data="{ type: 'video' }"
                  :show-file-list="false"
                  :on-success="
                    (response) => handleImageSuccess(response, 'videoCover')
                  "
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                >
                  <img
                    v-if="videoData.coverImage"
                    :src="videoData.coverImage"
                    class="uploaded-image"
                  />
                  <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-input
                  v-model="videoData.coverImage"
                  placeholder="或直接输入封面图片URL"
                  style="margin-top: 10px"
                />
              </div>
            </el-form-item>

            <el-form-item label="视频时长">
              <el-input v-model="videoData.duration" placeholder="如：03:45" />
            </el-form-item>

            <el-form-item label="视频描述">
              <el-input
                v-model="videoData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入视频描述"
              />
            </el-form-item>

            <el-form-item label="特色标签">
              <div class="tags-container">
                <el-tag
                  v-for="(tag, index) in videoData.features"
                  :key="index"
                  closable
                  @close="removeVideoTag(index)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="showTagInput"
                  ref="tagInput"
                  v-model="newTag"
                  size="small"
                  @keyup.enter="addVideoTag"
                  @blur="addVideoTag"
                  style="width: 100px"
                />
                <el-button v-else size="small" @click="showTagInput = true">
                  + 添加标签
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveVideoData"
                >保存视频设置</el-button
              >
              <el-button @click="resetVideoData">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 展会亮点管理 -->
      <el-tab-pane label="展会亮点" name="highlights" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>展会亮点设置</h3>
            <el-button type="primary" size="small" @click="addHighlight">
              <el-icon><Plus /></el-icon>
              添加亮点
            </el-button>
          </div>

          <el-table :data="highlightsData" border stripe>
            <el-table-column prop="title" label="标题" width="150" />
            <el-table-column prop="description" label="描述" width="300" />
            <el-table-column prop="icon" label="图标" width="100" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editHighlight(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteHighlight($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleHighlightStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 展区介绍管理 -->
      <el-tab-pane label="展区介绍" name="zones" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>展区介绍设置</h3>
            <el-button type="primary" size="small" @click="addZone">
              <el-icon><Plus /></el-icon>
              添加展区
            </el-button>
          </div>

          <el-table :data="zonesData" border stripe>
            <el-table-column prop="name" label="展区名称" width="150" />
            <el-table-column prop="description" label="描述" width="300" />
            <el-table-column label="展区图片" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.image"
                  fit="cover"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.image)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editZone(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteZone($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleZoneStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 合作伙伴管理 -->
      <el-tab-pane label="合作伙伴" name="partners" v-if="false">
        <div class="tab-content">
          <div class="section-header">
            <h3>合作伙伴设置</h3>
            <el-button type="primary" size="small" @click="addPartner">
              <el-icon><Plus /></el-icon>
              添加合作伙伴
            </el-button>
          </div>

          <el-table :data="partnersData" border stripe>
            <el-table-column prop="name" label="合作伙伴名称" width="200" />
            <el-table-column label="Logo" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.logo"
                  fit="contain"
                  style="
                    width: 80px;
                    height: 50px;
                    border-radius: 4px;
                    cursor: pointer;
                  "
                  @click="previewImage(row.logo)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editPartner(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deletePartner($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="togglePartnerStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editDialogTitle"
      width="600px"
    >
      <el-form :model="editForm" label-width="100px">
        <!-- 通用标题字段 -->
        <el-form-item
          label="标题"
          v-if="
            [
              'carousel',
              'event',
              'assistance',
              'gallery',
              'highlight',
              'liveImage',
            ].includes(editType)
          "
        >
          <el-input v-model="editForm.title" />
        </el-form-item>

        <!-- 副标题字段 -->
        <!-- <el-form-item label="副标题" v-if="['carousel', 'event'].includes(editType)">
          <el-input v-model="editForm.subtitle" />
        </el-form-item> -->

        <!-- 企业名称 -->
        <el-form-item label="企业名称" v-if="editType === 'exhibitor'">
          <el-input v-model="editForm.name" />
        </el-form-item>

        <!-- 展商评价：企业名称 -->
        <el-form-item label="企业名称" v-if="editType === 'testimonial'">
          <el-input v-model="editForm.company" />
        </el-form-item>

        <!-- 展区名称 -->
        <el-form-item label="展区名称" v-if="editType === 'zone'">
          <el-input v-model="editForm.name" />
        </el-form-item>

        <!-- 合作伙伴名称 -->
        <el-form-item label="合作伙伴名称" v-if="editType === 'partner'">
          <el-input v-model="editForm.name" />
        </el-form-item>

        <!-- 通用描述字段 -->
        <el-form-item
          label="描述"
          v-if="
            [
              'carousel',
              'event',
              'assistance',
              'gallery',
              'highlight',
              'zone',
              'liveImage',
            ].includes(editType)
          "
        >
          <el-input v-model="editForm.description" type="textarea" :rows="3" />
        </el-form-item>

        <!-- 展商评价：评价内容 -->
        <el-form-item label="评价内容" v-if="editType === 'testimonial'">
          <el-input v-model="editForm.content" type="textarea" :rows="4" />
        </el-form-item>

        <!-- 展商评价：图片上传 -->
        <el-form-item label="图片" v-if="editType === 'testimonial'">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'homepage' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'image')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.image"
                :src="editForm.image"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.image"
              placeholder="或直接输入图片URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 通用图片字段 -->
        <el-form-item
          label="图片"
          v-if="['carousel', 'event', 'liveImage'].includes(editType)"
        >
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'homepage' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'image')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.image"
                :src="editForm.image"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.image"
              placeholder="或直接输入图片URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 直播图片：跳转链接 -->
        <el-form-item label="跳转链接" v-if="editType === 'liveImage'">
          <el-input
            v-model="editForm.link"
            placeholder="可选，点击图片跳转的链接"
          />
        </el-form-item>

        <!-- 图片URL（用于轮播图） -->
        <el-form-item label="图片URL" v-if="editType === 'gallery'">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'gallery' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'url')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.url"
                :src="editForm.url"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.url"
              placeholder="或直接输入图片URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 企业Logo -->
        <el-form-item label="Logo" v-if="editType === 'exhibitor'">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'exhibitor' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'logo')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.logo"
                :src="editForm.logo"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.logo"
              placeholder="或直接输入Logo URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 展区图片 -->
        <el-form-item label="展区图片" v-if="editType === 'zone'">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'zone' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'image')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.image"
                :src="editForm.image"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.image"
              placeholder="或直接输入图片URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 合作伙伴Logo -->
        <el-form-item label="Logo" v-if="editType === 'partner'">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'partner' }"
              :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response, 'logo')"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="editForm.logo"
                :src="editForm.logo"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="editForm.logo"
              placeholder="或直接输入Logo URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <!-- 分组（企业轮播） -->
        <el-form-item label="分组" v-if="editType === 'exhibitor'">
          <el-input-number v-model="editForm.group" :min="1" />
        </el-form-item>

        <!-- 按钮文字 -->
        <el-form-item
          label="按钮文字"
          v-if="['carousel', 'event'].includes(editType)"
        >
          <el-input v-model="editForm.buttonText" />
        </el-form-item>

        <!-- 跳转动作 -->
        <el-form-item label="跳转动作" v-if="editType === 'carousel'">
          <el-input
            v-model="editForm.action"
            placeholder="如：register, visitor, contact 或直接填写路径"
          />
        </el-form-item>

        <!-- 跳转链接 -->
        <el-form-item label="跳转链接" v-if="editType === 'carousel'">
          <el-input
            v-model="editForm.link"
            placeholder="如：https://example.com 或 /about"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px">
            优先级：跳转链接 > 跳转动作。支持外部链接(http/https)和内部路径(/)
          </div>
        </el-form-item>

        <!-- 跳转链接 -->
        <el-form-item label="跳转链接" v-if="editType === 'assistance'">
          <el-input v-model="editForm.link" />
        </el-form-item>

        <!-- 图标 -->
        <el-form-item
          label="图标"
          v-if="['assistance', 'highlight'].includes(editType)"
        >
          <el-input v-model="editForm.icon" />
        </el-form-item>

        <!-- 合作伙伴相关字段 -->
        <el-form-item label="官网" v-if="editType === 'partner'">
          <el-input v-model="editForm.website" />
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序">
          <el-input-number v-model="editForm.sort" :min="1" />
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="60%"
      :before-close="closeImagePreview"
      class="image-preview-dialog"
    >
      <div class="image-preview-content">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { homepageApi, uploadApi } from "@/api/admin";
import {
  Check,
  View,
  Plus,
  Delete,
  Edit,
  OfficeBuilding,
  User,
  Location,
  Timer,
  Upload,
  Download,
} from "@element-plus/icons-vue";
import config from "@/config";

// 权限检查
const hasPermission = (permission) => {
  const adminUser = localStorage.getItem("adminUser");
  if (!adminUser) return false;
  try {
    const userData = JSON.parse(adminUser);
    return (
      userData.permissions?.includes("all") ||
      userData.permissions?.includes(permission)
    );
  } catch {
    return false;
  }
};

// 响应式数据
const activeTab = ref("carousel");
const editDialogVisible = ref(false);
const editDialogTitle = ref("");
const editType = ref("");
const editForm = reactive({});
const showTagInput = ref(false);
const newTag = ref("");

// 图片上传相关
const apiConfig = config.getApiConfig();
const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`);
const videoUploadAction = ref(`${apiConfig.baseURL}/api/upload/video`);
const uploadHeaders = ref({
  token: localStorage.getItem("adminToken") || "",
});
const videoUploading = ref(false);

// 图片预览相关
const imagePreviewVisible = ref(false);
const previewImageUrl = ref("");

// 轮播图数据
const carouselData = ref([]);

// 展会主视觉数据
const mainVisualData = reactive({
  title: "",
  subtitle: "",
  image: "",
  stats: [],
});

// 展会概览数据
const overviewData = reactive({
  items: [],
});

// 重点活动数据
const eventsData = ref([]);

// 参展企业轮播数据
const exhibitorsData = ref([]);
const exhibitorImportRef = ref(null);

// 展商评价数据
const testimonialsData = ref([]);

// 展会协助数据
const assistanceData = ref([
  {
    id: 1,
    title: "展位图",
    description: "查看展位分布和预订情况",
    icon: "Grid",
    link: "/exhibitors",
    sort: 1,
    status: "active",
  },
  {
    id: 2,
    title: "观众登记",
    description: "在线登记参观展会",
    icon: "User",
    link: "/visitors",
    sort: 2,
    status: "active",
  },
  {
    id: 3,
    title: "交通",
    description: "展馆交通指南",
    icon: "Location",
    link: "/visitors",
    sort: 3,
    status: "active",
  },
  {
    id: 4,
    title: "联系我们",
    description: "获取更多展会信息",
    icon: "Phone",
    link: "/contact",
    sort: 4,
    status: "active",
  },
]);

// 展会图片轮播数据
const galleryData = ref([
  {
    id: 1,
    title: "开幕式盛况",
    description: "2025年展会开幕式现场",
    url: "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=1200&h=400&fit=crop",
    sort: 1,
    status: "active",
  },
  {
    id: 2,
    title: "展商交流",
    description: "展商之间的深入交流",
    url: "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=1200&h=400&fit=crop",
    sort: 2,
    status: "active",
  },
  {
    id: 3,
    title: "观众参观",
    description: "专业观众参观展会",
    url: "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=1200&h=400&fit=crop",
    sort: 3,
    status: "active",
  },
]);

// 展会现场直播数据
const liveData = reactive({
  title: "展会现场照片直播",
  subtitle: "实时观看展会精彩瞬间",
  status: "LIVE",
  viewers: "1,234",
  images: [
    {
      id: 1,
      title: "开幕式盛况",
      description: "2025年展会开幕式现场",
      url: "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=800&h=450&fit=crop",
      sort: 1,
      status: "active",
    },
    {
      id: 2,
      title: "展商交流",
      description: "展商之间的深入交流",
      url: "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=800&h=450&fit=crop",
      sort: 2,
      status: "active",
    },
    {
      id: 3,
      title: "观众参观",
      description: "专业观众参观展会",
      url: "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=800&h=450&fit=crop",
      sort: 3,
      status: "active",
    },
  ],
});

// 直播查询表单
const liveQueryForm = reactive({
  title: "",
  status: "",
  viewers: "",
});

// 过滤后的直播图片列表
const filteredLiveImages = computed(() => {
  let images = liveData.images;

  if (liveQueryForm.title) {
    images = images.filter((img) => img.title.includes(liveQueryForm.title));
  }

  if (liveQueryForm.status) {
    images = images.filter((img) => img.status === liveQueryForm.status);
  }

  if (liveQueryForm.viewers) {
    images = images.filter((img) =>
      liveData.viewers.includes(liveQueryForm.viewers)
    );
  }

  return images;
});

// 宣传视频数据
const videoData = reactive({
  title: "FAIR plus机器人全产业链接会 2025",
  subtitle: "官方宣传片",
  videoUrl: "https://www.sciif.com/upload/2025/07/01/171980475466m26n9.mp4",
  coverImage:
    "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=800&h=450&fit=crop",
  duration: "03:45",
  description: "点击播放展会宣传片",
  features: ["4K高清", "官方制作", "精彩回顾"],
});

// 展会亮点数据
const highlightsData = ref([
  {
    id: 1,
    icon: "Trophy",
    title: "行业权威",
    description: "汇聚全球顶尖工业企业和创新技术",
    sort: 1,
    status: "active",
  },
  {
    id: 2,
    icon: "User",
    title: "专业观众",
    description: "吸引50,000+专业观众参与",
    sort: 2,
    status: "active",
  },
  {
    id: 3,
    icon: "Setting",
    title: "技术前沿",
    description: "展示最新工业4.0技术和解决方案",
    sort: 3,
    status: "active",
  },
]);

// 展区介绍数据
const zonesData = ref([
  {
    id: 1,
    name: "智能制造展区",
    description: "展示最新工业4.0技术和解决方案",
    image:
      "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=400&h=300&fit=crop",
    features: ["机器人技术", "自动化设备", "智能控制系统"],
    sort: 1,
    status: "active",
  },
  {
    id: 2,
    name: "工业自动化展区",
    description: "展示工业自动化设备和解决方案",
    image:
      "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=400&h=300&fit=crop",
    features: ["PLC系统", "传感器技术", "工业软件"],
    sort: 2,
    status: "active",
  },
]);

// 合作伙伴数据
const partnersData = ref([
  {
    id: 1,
    name: "工业协会",
    logo: "https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=200&h=100&fit=crop",
    website: "https://www.industry.org",
    sort: 1,
    status: "active",
  },
  {
    id: 2,
    name: "科技联盟",
    logo: "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=200&h=100&fit=crop",
    website: "https://www.tech-alliance.org",
    sort: 2,
    status: "active",
  },
]);

// 方法
const handleSaveAll = async () => {
  try {
    await ElMessageBox.confirm("确定要保存所有更改吗？", "确认操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const savePromises = [];
    let hasChanges = false;

    // 1. 保存展会主视觉数据
    if (
      mainVisualData.title ||
      mainVisualData.subtitle ||
      mainVisualData.image ||
      (mainVisualData.stats && mainVisualData.stats.length > 0)
    ) {
      const mainVisualFormData = {
        contentType: "main_visual",
        title: mainVisualData.title,
        subtitle: mainVisualData.subtitle,
        imageUrl: mainVisualData.image,
        content: JSON.stringify({
          stats: mainVisualData.stats,
        }),
        sortOrder: 1,
        status: "active",
      };

      // 检查是否已存在主视觉数据
      const existingMainVisual = await homepageApi.getContentByType(
        "main_visual"
      );
      if (
        existingMainVisual &&
        existingMainVisual.data &&
        existingMainVisual.data.length > 0
      ) {
        const existing = existingMainVisual.data[0];
        // 检查是否有实际变更
        const hasMainVisualChanges =
          existing.title !== mainVisualData.title ||
          existing.subtitle !== mainVisualData.subtitle ||
          existing.imageUrl !== mainVisualData.image ||
          JSON.stringify(JSON.parse(existing.content || "{}").stats || []) !==
            JSON.stringify(mainVisualData.stats || []);

        if (hasMainVisualChanges) {
          mainVisualFormData.id = existing.id;
          savePromises.push(homepageApi.updateContent(mainVisualFormData));
          hasChanges = true;
        }
      } else {
        savePromises.push(homepageApi.createContent(mainVisualFormData));
        hasChanges = true;
      }
    }

    // 2. 保存展会概览数据
    if (overviewData.items && overviewData.items.length > 0) {
      const overviewFormData = {
        contentType: "overview",
        title: "展会概览",
        subtitle: "展会基本情况统计",
        content: JSON.stringify({
          items: overviewData.items,
        }),
        sortOrder: 2,
        status: "active",
      };

      const existingOverview = await homepageApi.getContentByType("overview");
      if (
        existingOverview &&
        existingOverview.data &&
        existingOverview.data.length > 0
      ) {
        const existing = existingOverview.data[0];
        const hasOverviewChanges =
          existing.content !== JSON.stringify({ items: overviewData.items });
        if (hasOverviewChanges) {
          overviewFormData.id = existing.id;
          savePromises.push(homepageApi.updateContent(overviewFormData));
          hasChanges = true;
        }
      } else {
        savePromises.push(homepageApi.createContent(overviewFormData));
        hasChanges = true;
      }
    }

    // 3. 保存参展企业轮播数据（逐条增改，不删除其他）
    if (
      exhibitorsData &&
      exhibitorsData.value &&
      exhibitorsData.value.length > 0
    ) {
      for (const ex of exhibitorsData.value) {
        const exhibitorFormData = {
          contentType: "exhibitors",
          title: ex.name,
          imageUrl: ex.logo,
          content: JSON.stringify({ group: Number(ex.group || 1) }),
          sortOrder: ex.sort || 0,
          status: ex.status || "active",
        };
        if (ex.id) {
          exhibitorFormData.id = ex.id;
          savePromises.push(homepageApi.updateContent(exhibitorFormData));
        } else {
          savePromises.push(homepageApi.createContent(exhibitorFormData));
        }
        hasChanges = true;
      }
    }

    // 4. 保存重点活动数据（已隐藏，保留兼容）
    if (eventsData && eventsData.length > 0) {
      for (const event of eventsData) {
        const eventFormData = {
          contentType: "events",
          title: event.title,
          subtitle: event.subtitle || "",
          imageUrl: event.image,
          content: JSON.stringify({
            description: event.description,
            buttonText: event.buttonText,
            date: event.date,
            location: event.location,
          }),
          sortOrder: event.sort || 0,
          status: event.status || "active",
        };

        if (event.id) {
          eventFormData.id = event.id;
          savePromises.push(homepageApi.updateContent(eventFormData));
        } else {
          savePromises.push(homepageApi.createContent(eventFormData));
        }
        hasChanges = true;
      }
    }

    // 5. 保存展会协助数据（已隐藏，保留兼容）
    if (assistanceData && assistanceData.length > 0) {
      for (const assistance of assistanceData) {
        const assistanceFormData = {
          contentType: "assistance",
          title: assistance.title,
          content: JSON.stringify({
            description: assistance.description,
            icon: assistance.icon,
            link: assistance.link,
          }),
          sortOrder: assistance.sort || 0,
          status: assistance.status || "active",
        };

        if (assistance.id) {
          assistanceFormData.id = assistance.id;
          savePromises.push(homepageApi.updateContent(assistanceFormData));
        } else {
          savePromises.push(homepageApi.createContent(assistanceFormData));
        }
        hasChanges = true;
      }
    }

    // 6. 保存展会图片轮播数据（已隐藏，保留兼容）
    if (galleryData && galleryData.length > 0) {
      for (const gallery of galleryData) {
        const galleryFormData = {
          contentType: "gallery",
          title: gallery.title,
          imageUrl: gallery.url,
          content: JSON.stringify({
            description: gallery.description,
          }),
          sortOrder: gallery.sort || 0,
          status: gallery.status || "active",
        };

        if (gallery.id) {
          galleryFormData.id = gallery.id;
          savePromises.push(homepageApi.updateContent(galleryFormData));
        } else {
          savePromises.push(homepageApi.createContent(galleryFormData));
        }
        hasChanges = true;
      }
    }

    // 7. 保存展会现场直播数据
    if (
      liveData.title ||
      liveData.subtitle ||
      (liveData.images && liveData.images.length > 0)
    ) {
      const liveFormData = {
        contentType: "live",
        title: liveData.title,
        subtitle: liveData.subtitle,
        content: JSON.stringify({
          status: liveData.status,
          viewers: liveData.viewers,
          images: liveData.images.filter((img) => img.status === "active"),
        }),
        sortOrder: 6,
        status: "active",
      };

      const existingLive = await homepageApi.getContentByType("live");
      if (existingLive && existingLive.data && existingLive.data.length > 0) {
        const existing = existingLive.data[0];
        const hasLiveChanges =
          existing.content !==
          JSON.stringify({
            status: liveData.status,
            viewers: liveData.viewers,
            images: liveData.images.filter((img) => img.status === "active"),
          });
        if (hasLiveChanges) {
          liveFormData.id = existing.id;
          savePromises.push(homepageApi.updateContent(liveFormData));
          hasChanges = true;
        }
      } else {
        savePromises.push(homepageApi.createContent(liveFormData));
        hasChanges = true;
      }
    }

    // 8. 保存宣传视频数据
    if (
      videoData.title ||
      videoData.subtitle ||
      videoData.videoUrl ||
      videoData.coverImage
    ) {
      const videoFormData = {
        contentType: "video",
        title: videoData.title,
        subtitle: videoData.subtitle || "",
        imageUrl: videoData.coverImage,
        content: JSON.stringify({
          videoUrl: videoData.videoUrl,
          duration: videoData.duration,
          description: videoData.description,
          tags: videoData.tags,
        }),
        sortOrder: 1,
        status: "active",
      };

      const existingVideo = await homepageApi.getContentByType("video");
      if (
        existingVideo &&
        existingVideo.data &&
        existingVideo.data.length > 0
      ) {
        const existing = existingVideo.data[0];
        const hasVideoChanges =
          existing.title !== videoData.title ||
          existing.subtitle !== videoData.subtitle ||
          existing.imageUrl !== videoData.coverImage ||
          JSON.stringify(JSON.parse(existing.content || "{}")) !==
            JSON.stringify({
              videoUrl: videoData.videoUrl,
              duration: videoData.duration,
              description: videoData.description,
              tags: videoData.tags,
            });

        if (hasVideoChanges) {
          videoFormData.id = existing.id;
          savePromises.push(homepageApi.updateContent(videoFormData));
          hasChanges = true;
        }
      } else {
        savePromises.push(homepageApi.createContent(videoFormData));
        hasChanges = true;
      }
    }

    // 9. 保存展商评价数据
    if (
      testimonialsData &&
      testimonialsData.value &&
      testimonialsData.value.length > 0
    ) {
      for (const t of testimonialsData.value) {
        const testimonialFormData = {
          contentType: "testimonials",
          title: t.company,
          imageUrl: t.image,
          content: JSON.stringify({ content: t.content }),
          sortOrder: t.sort || 0,
          status: t.status || "active",
        };
        if (t.id) {
          testimonialFormData.id = t.id;
          savePromises.push(homepageApi.updateContent(testimonialFormData));
        } else {
          savePromises.push(homepageApi.createContent(testimonialFormData));
        }
        hasChanges = true;
      }
    }

    // 10. 保存展会亮点数据（已隐藏，保留兼容）
    if (highlightsData && highlightsData.length > 0) {
      for (const highlight of highlightsData) {
        const highlightFormData = {
          contentType: "highlights",
          title: highlight.title,
          content: JSON.stringify({
            description: highlight.description,
            icon: highlight.icon,
          }),
          sortOrder: highlight.sort || 0,
          status: highlight.status || "active",
        };

        if (highlight.id) {
          highlightFormData.id = highlight.id;
          savePromises.push(homepageApi.updateContent(highlightFormData));
        } else {
          savePromises.push(homepageApi.createContent(highlightFormData));
        }
        hasChanges = true;
      }
    }

    // 11. 保存展区介绍数据（已隐藏，保留兼容）
    if (zonesData && zonesData.length > 0) {
      for (const zone of zonesData) {
        const zoneFormData = {
          contentType: "zones",
          title: zone.name,
          imageUrl: zone.image,
          content: JSON.stringify({
            description: zone.description,
          }),
          sortOrder: zone.sort || 0,
          status: zone.status || "active",
        };

        if (zone.id) {
          zoneFormData.id = zone.id;
          savePromises.push(homepageApi.updateContent(zoneFormData));
        } else {
          savePromises.push(homepageApi.createContent(zoneFormData));
        }
        hasChanges = true;
      }
    }

    // 12. 保存合作伙伴数据（已隐藏，保留兼容）
    if (partnersData && partnersData.length > 0) {
      for (const partner of partnersData) {
        const partnerFormData = {
          contentType: "partners",
          title: partner.name,
          imageUrl: partner.logo,
          content: JSON.stringify({
            description: partner.description,
            website: partner.website,
          }),
          sortOrder: partner.sort || 0,
          status: partner.status || "active",
        };

        if (partner.id) {
          partnerFormData.id = partner.id;
          savePromises.push(homepageApi.updateContent(partnerFormData));
        } else {
          savePromises.push(homepageApi.createContent(partnerFormData));
        }
        hasChanges = true;
      }
    }

    // 执行所有保存操作
    if (savePromises.length > 0 && hasChanges) {
      await Promise.all(savePromises);
      ElMessage.success(`成功保存 ${savePromises.length} 项更改`);

      // 重新加载数据
      await loadHomepageContent();
      await loadOtherContent();
    } else {
      ElMessage.info("没有需要保存的更改");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("保存所有更改失败:", error);
      ElMessage.error("保存失败: " + (error.message || "未知错误"));
    }
  }
};

const handlePreview = () => {
  window.open("/", "_blank");
};

// 图片预览方法
const previewImage = (imageUrl) => {
  if (imageUrl) {
    previewImageUrl.value = imageUrl;
    imagePreviewVisible.value = true;
  }
};

const closeImagePreview = () => {
  imagePreviewVisible.value = false;
  previewImageUrl.value = "";
};

// 数据加载方法
const loading = ref(false);

const loadHomepageContent = async () => {
  loading.value = true;
  try {
    // 加载轮播图数据
    const carouselResponse = await homepageApi.getContentByType("carousel");
    if (carouselResponse && carouselResponse.data) {
      carouselData.value = carouselResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          title: item.title,
          subtitle: item.subtitle || contentData.subtitle || "",
          description: contentData.description || item.subtitle || "",
          image: item.imageUrl,
          buttonText: contentData.buttonText || "",
          action: contentData.action || "",
          link: contentData.link || "",
          sort: item.sortOrder,
          status: item.status,
        };
      });
    }

    // 加载展会主视觉数据
    const mainVisualResponse = await homepageApi.getContentByType(
      "main_visual"
    );
    if (
      mainVisualResponse &&
      mainVisualResponse.data &&
      mainVisualResponse.data.length > 0
    ) {
      const mainVisual = mainVisualResponse.data[0];
      const extraData = JSON.parse(mainVisual.extraData || "{}");
      Object.assign(mainVisualData, {
        title: mainVisual.title,
        subtitle: mainVisual.subtitle,
        image: mainVisual.imageUrl,
        stats: extraData.stats || [],
      });
    }

    // 加载展会概览数据
    const overviewResponse = await homepageApi.getContentByType("overview");
    if (
      overviewResponse &&
      overviewResponse.data &&
      overviewResponse.data.length > 0
    ) {
      const overview = overviewResponse.data[0];
      if (overview.content) {
        try {
          const contentData = JSON.parse(overview.content);
          if (contentData.items && Array.isArray(contentData.items)) {
            overviewData.items = contentData.items.map((item) => ({
              id: item.id || "",
              title: item.title || "",
              value: item.value || "",
              sort: item.sort || 1,
            }));
          } else if (contentData.stats && Array.isArray(contentData.stats)) {
            // 兼容旧格式的stats数据
            overviewData.items = contentData.stats.map((stat) => ({
              id: "",
              title: stat.label || "",
              value: stat.number || "",
              sort: 1,
            }));
          }
        } catch (error) {
          console.error("解析展会概览数据失败:", error);
          // 使用默认数据
          overviewData.items = [
            { id: "", title: "展会面积", value: "15000m²", sort: 1 },
            { id: "", title: "展商数量", value: "500+", sort: 2 },
            { id: "", title: "观众数量", value: "50000+", sort: 3 },
            { id: "", title: "海外观展团", value: "100+", sort: 4 },
            { id: "", title: "同期活动", value: "40+", sort: 5 },
          ];
        }
      }
    } else {
      // 如果没有数据，使用默认数据
      overviewData.items = [
        { id: "", title: "展会面积", value: "15000m²", sort: 1 },
        { id: "", title: "展商数量", value: "500+", sort: 2 },
        { id: "", title: "观众数量", value: "50000+", sort: 3 },
        { id: "", title: "海外观展团", value: "100+", sort: 4 },
        { id: "", title: "同期活动", value: "40+", sort: 5 },
      ];
    }

    // 加载其他数据
    await loadOtherContent();
  } catch (error) {
    console.error("加载首页内容失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

const loadOtherContent = async () => {
  try {
    // 加载展商评价
    const testimonialsResponse = await homepageApi.getContentByType(
      "testimonials"
    );
    if (
      testimonialsResponse &&
      testimonialsResponse.code === "200" &&
      testimonialsResponse.data
    ) {
      testimonialsData.value = testimonialsResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          company: item.title || contentData.company || "",
          content: contentData.content || item.subtitle || "",
          image: item.imageUrl || contentData.image || "",
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载重点活动
    const eventsResponse = await homepageApi.getContentByType("events");
    if (
      eventsResponse &&
      eventsResponse.code === "200" &&
      eventsResponse.data
    ) {
      // 转换数据格式以匹配前端期望
      eventsData.value = eventsResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          title: item.title,
          description: contentData.description || item.subtitle,
          image: item.imageUrl,
          buttonText: contentData.buttonText || "了解更多",
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载参展企业（contentType: exhibitors）
    const exhibitorsResponse = await homepageApi.getContentByType("exhibitors");
    if (
      exhibitorsResponse &&
      exhibitorsResponse.code === "200" &&
      exhibitorsResponse.data
    ) {
      // 转换数据格式以匹配前端期望
      exhibitorsData.value = exhibitorsResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          name: item.title || contentData.name || "",
          logo: item.imageUrl || contentData.logo || "",
          group: Number(contentData.group || 1),
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载展会协助
    const assistanceResponse = await homepageApi.getContentByType("assistance");
    if (
      assistanceResponse &&
      assistanceResponse.code === "200" &&
      assistanceResponse.data
    ) {
      // 转换数据格式以匹配前端期望
      assistanceData.value = assistanceResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          title: item.title,
          description: contentData.description || item.subtitle,
          icon: contentData.icon || "setting",
          link: item.linkUrl,
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载宣传视频数据
    const videoResponse = await homepageApi.getContentByType("video");
    if (
      videoResponse &&
      videoResponse.code === "200" &&
      videoResponse.data &&
      videoResponse.data.length > 0
    ) {
      const video = videoResponse.data[0];
      const contentData = video.content ? JSON.parse(video.content) : {};
      Object.assign(videoData, {
        title: video.title || "",
        subtitle: video.subtitle || "",
        videoUrl: contentData.videoUrl || "",
        coverImage: video.imageUrl || "",
        duration: contentData.duration || "",
        description: contentData.description || "",
        features: contentData.tags || [],
      });
    }

    // 加载展会图片轮播数据
    const galleryResponse = await homepageApi.getContentByType("gallery");
    if (
      galleryResponse &&
      galleryResponse.code === "200" &&
      galleryResponse.data
    ) {
      galleryData.value = galleryResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          title: item.title,
          description: contentData.description || "",
          url: item.imageUrl,
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载展会现场直播数据
    const liveResponse = await homepageApi.getContentByType("live");
    if (
      liveResponse &&
      liveResponse.code === "200" &&
      liveResponse.data &&
      liveResponse.data.length > 0
    ) {
      const live = liveResponse.data[0];
      if (live.content) {
        try {
          const contentData = JSON.parse(live.content);
          Object.assign(liveData, {
            title: live.title || "",
            subtitle: live.subtitle || "",
            status: contentData.status || "LIVE",
            viewers: contentData.viewers || "0",
            images: (contentData.images || []).map((img, idx) => ({
              id: img.id || undefined,
              title: img.title || "",
              description: img.description || "",
              url: img.url || img.image || "",
              link: img.link || "",
              sort: img.sort || idx + 1,
              status: img.status || "active",
            })),
          });
        } catch (error) {
          console.error("解析展会现场直播数据失败:", error);
        }
      }
    }

    // 加载展会亮点数据
    const highlightsResponse = await homepageApi.getContentByType("highlights");
    if (
      highlightsResponse &&
      highlightsResponse.code === "200" &&
      highlightsResponse.data
    ) {
      highlightsData.value = highlightsResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          title: item.title,
          description: contentData.description || "",
          icon: contentData.icon || "Trophy",
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载展区介绍数据
    const zonesResponse = await homepageApi.getContentByType("zones");
    if (zonesResponse && zonesResponse.code === "200" && zonesResponse.data) {
      zonesData.value = zonesResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          name: item.title,
          description: contentData.description || "",
          image: item.imageUrl,
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    // 加载合作伙伴数据
    const partnersResponse = await homepageApi.getContentByType("partners");
    if (
      partnersResponse &&
      partnersResponse.code === "200" &&
      partnersResponse.data
    ) {
      partnersData.value = partnersResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          name: item.title,
          description: contentData.description || "",
          logo: item.imageUrl,
          website: contentData.website || "",
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }

    console.log("重点活动数据加载完成:", eventsData.value);
  } catch (error) {
    console.error("加载其他内容失败:", error);
  }
};

// 单独加载参展企业数据
const loadExhibitorsData = async () => {
  try {
    const exhibitorsResponse = await homepageApi.getContentByType("exhibitors");
    if (
      exhibitorsResponse &&
      exhibitorsResponse.code === "200" &&
      exhibitorsResponse.data
    ) {
      // 转换数据格式以匹配前端期望
      exhibitorsData.value = exhibitorsResponse.data.map((item) => {
        const contentData = item.content ? JSON.parse(item.content) : {};
        return {
          id: item.id,
          name: item.title,
          logo: item.imageUrl,
          group: contentData.group || 1,
          sort: item.sortOrder || 0,
          status: item.status || "active",
        };
      });
    }
  } catch (error) {
    console.error("加载参展企业数据失败:", error);
  }
};

// 图片上传相关方法
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 15;

  if (!isImage) {
    ElMessage.error("只能上传图片格式的文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 15MB!");
    return false;
  }
  return true;
};

const handleImageSuccess = (response, field) => {
  if (response && (response.code === "200" || response.code === 200)) {
    if (field === "mainVisual") {
      mainVisualData.image = response.data.url;
    } else if (field === "videoCover") {
      videoData.coverImage = response.data.url;
    } else {
      editForm[field] = response.data.url;
    }
    ElMessage.success("图片上传成功!");
  } else {
    ElMessage.error("图片上传失败!");
  }
};

// 视频上传相关方法
const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith("video/");
  const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isVideo) {
    ElMessage.error("只能上传视频格式的文件!");
    return false;
  }
  if (!isLt100M) {
    ElMessage.error("视频大小不能超过 100MB!");
    return false;
  }
  videoUploading.value = true;
  return true;
};

const handleVideoSuccess = (response) => {
  videoUploading.value = false;
  if (response && (response.code === "200" || response.code === 200)) {
    videoData.videoUrl = response.data.url;
    ElMessage.success("视频上传成功!");
  } else {
    ElMessage.error("视频上传失败!");
  }
};

// 保存视频数据
const saveVideoData = async () => {
  try {
    const formData = {
      contentType: "video",
      title: videoData.title,
      subtitle: videoData.subtitle || "",
      imageUrl: videoData.coverImage,
      content: JSON.stringify({
        videoUrl: videoData.videoUrl,
        duration: videoData.duration,
        description: videoData.description,
        tags: videoData.features,
      }),
      sortOrder: 1,
      status: "active",
    };

    // 检查是否已存在视频数据
    const existingResponse = await homepageApi.getContentByType("video");
    if (
      existingResponse &&
      existingResponse.data &&
      existingResponse.data.length > 0
    ) {
      // 更新现有数据
      formData.id = existingResponse.data[0].id;
      await homepageApi.updateContent(formData);
    } else {
      // 创建新数据
      await homepageApi.createContent(formData);
    }

    ElMessage.success("视频设置保存成功");
  } catch (error) {
    console.error("保存视频设置失败:", error);
    ElMessage.error("保存失败: " + (error.message || "未知错误"));
  }
};

// 重置视频数据
const resetVideoData = () => {
  Object.assign(videoData, {
    title: "",
    subtitle: "",
    videoUrl: "",
    coverImage: "",
    duration: "",
    description: "",
    features: [],
  });
  ElMessage.info("已重置视频设置");
};

// 组件挂载时加载数据
onMounted(() => {
  loadHomepageContent();
  loadOtherContent();
});

// 轮播图管理
const addCarouselItem = () => {
  editType.value = "carousel";
  editDialogTitle.value = "添加轮播图";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    subtitle: "",
    description: "",
    image: "",
    buttonText: "",
    action: "",
    link: "",
    sort: carouselData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editCarouselItem = (row) => {
  editType.value = "carousel";
  editDialogTitle.value = "编辑轮播图";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteCarouselItem = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个轮播图吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = carouselData.value[index];
    if (item.id) {
      // 如果有ID，调用API删除
      const response = await homepageApi.deleteContent(item.id);
      if (response && response.code === "200") {
        carouselData.value.splice(index, 1);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败");
      }
    } else {
      // 如果没有ID，直接删除
      carouselData.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除轮播图失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleCarouselStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 展会主视觉管理
const addVisualStat = () => {
  mainVisualData.stats.push({ value: "", label: "" });
};

const removeVisualStat = (index) => {
  mainVisualData.stats.splice(index, 1);
};

// 保存主视觉设置
const saveMainVisual = async () => {
  try {
    const formData = {
      contentType: "main_visual",
      title: mainVisualData.title,
      subtitle: mainVisualData.subtitle,
      imageUrl: mainVisualData.image,
      content: JSON.stringify({
        stats: mainVisualData.stats,
      }),
      sortOrder: 1,
      status: "active",
    };

    // 检查是否已存在主视觉数据
    const existingResponse = await homepageApi.getContentByType("main_visual");
    if (
      existingResponse &&
      existingResponse.data &&
      existingResponse.data.length > 0
    ) {
      // 更新现有数据
      formData.id = existingResponse.data[0].id;
      await homepageApi.updateContent(formData);
    } else {
      // 创建新数据
      await homepageApi.createContent(formData);
    }

    ElMessage.success("主视觉设置保存成功");
  } catch (error) {
    console.error("保存主视觉设置失败:", error);
    ElMessage.error("保存失败: " + (error.message || "未知错误"));
  }
};

// 重置主视觉设置
const resetMainVisual = () => {
  Object.assign(mainVisualData, {
    title: "",
    subtitle: "",
    image: "",
    stats: [],
  });
  ElMessage.info("已重置主视觉设置");
};

// 展会概览管理
const addOverviewItem = () => {
  overviewData.items.push({
    id: "",
    title: "",
    value: "",
    sort: overviewData.items.length + 1,
  });
};

const deleteOverviewItem = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个统计项吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = overviewData.items[index];
    if (item.id) {
      // 如果有ID，调用API删除
      await homepageApi.deleteContent(item.id);
    }

    overviewData.items.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const editOverviewItem = (index) => {
  const item = overviewData.items[index];
  ElMessage.info(`正在编辑: ${item.title || "统计项" + (index + 1)}`);
};

// 展会现场直播图片管理
const addLiveImage = () => {
  editType.value = "liveImage";
  editDialogTitle.value = "添加直播图片";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    description: "",
    image: "",
    url: "",
    link: "",
    sort: liveData.images.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editLiveImage = (row, index) => {
  editType.value = "liveImage";
  editDialogTitle.value = "编辑直播图片";
  Object.assign(editForm, {
    ...row,
    __index: index,
    image: row.url, // 确保图片字段正确映射
    title: row.title || "",
    description: row.description || "",
    link: row.link || "",
    sort: row.sort || index + 1,
    status: row.status || "active",
  });
  editDialogVisible.value = true;
};

const deleteLiveImage = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个直播图片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 从本地数组中删除
    liveData.images.splice(index, 1);

    // 立即持久化 live 数据
    try {
      const existingLive = await homepageApi.getContentByType("live");
      const liveFormData = {
        contentType: "live",
        title: liveData.title,
        subtitle: liveData.subtitle,
        content: JSON.stringify({
          status: liveData.status,
          viewers: liveData.viewers,
          images: liveData.images.filter((img) => img.status === "active"),
        }),
        sortOrder: 6,
        status: "active",
      };

      if (existingLive && existingLive.data && existingLive.data.length > 0) {
        liveFormData.id = existingLive.data[0].id;
        await homepageApi.updateContent(liveFormData);
      } else {
        await homepageApi.addContent(liveFormData);
      }

      ElMessage.success("删除成功");
    } catch (e) {
      console.error("删除失败:", e);
      ElMessage.error("删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleLiveImageStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 直播查询方法
const searchLiveData = () => {
  // 查询逻辑已在computed中实现，这里可以添加额外的查询逻辑
  ElMessage.success("查询完成");
};

const resetLiveQuery = () => {
  Object.assign(liveQueryForm, {
    title: "",
    status: "",
    viewers: "",
  });
  ElMessage.info("查询条件已重置");
};

// 重点活动管理
const addEvent = () => {
  editType.value = "event";
  editDialogTitle.value = "添加活动";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    description: "",
    image: "",
    buttonText: "",
    sort: eventsData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

// 展商评价管理
const addTestimonial = () => {
  editType.value = "testimonial";
  editDialogTitle.value = "添加展商评价";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    company: "",
    content: "",
    image: "",
    sort: testimonialsData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editTestimonial = (row) => {
  editType.value = "testimonial";
  editDialogTitle.value = "编辑展商评价";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteTestimonial = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个评价吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = testimonialsData.value[index];
    if (item && item.id) {
      await homepageApi.deleteContent(item.id);
    }

    testimonialsData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleTestimonialStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

const editEvent = (row) => {
  editType.value = "event";
  editDialogTitle.value = "编辑活动";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteEvent = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个活动吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const event = eventsData.value[index];
    if (event.id) {
      // 如果有ID，调用API删除
      await homepageApi.deleteContent(event.id);
    }

    eventsData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleEventStatus = async (row) => {
  try {
    const newStatus = row.status === "active" ? "inactive" : "active";

    if (row.id) {
      // 调用API更新状态
      await homepageApi.updateContentStatus(row.id, newStatus);
    }

    row.status = newStatus;
    ElMessage.success("状态更新成功");
  } catch (error) {
    console.error("状态更新失败:", error);
    ElMessage.error("状态更新失败");
  }
};

// 参展企业轮播管理
const addExhibitor = () => {
  editType.value = "exhibitor";
  editDialogTitle.value = "添加企业";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    name: "",
    logo: "",
    group: 1,
    sort: exhibitorsData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editExhibitor = (row) => {
  editType.value = "exhibitor";
  editDialogTitle.value = "编辑企业";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteExhibitor = async (index) => {
  try {
    const item = exhibitorsData.value[index];
    if (item && item.id) {
      await homepageApi.deleteContent(item.id);
    }
    exhibitorsData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (e) {
    console.error("删除企业失败:", e);
    ElMessage.error("删除失败");
  }
};

const toggleExhibitorStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 参展企业批量导入功能
const downloadExhibitorTemplate = () => {
  // 创建CSV模板
  const headers = ["企业名称", "企业Logo链接", "分组", "状态"];
  const template = [
    headers,
    ["示例企业1", "https://example.com/logo1.jpg", "1", "启用"],
    ["示例企业2", "https://example.com/logo2.jpg", "1", "启用"],
    ["示例企业3", "", "2", "启用"],
    ["示例企业4", "", "2", "禁用"],
  ];

  // 转换为CSV格式，正确处理包含逗号的字段
  const csvContent = template
    .map((row) =>
      row
        .map((cell) => {
          // 如果字段包含逗号、引号或换行符，需要用引号包围
          if (cell.includes(",") || cell.includes('"') || cell.includes("\n")) {
            return `"${cell.replace(/"/g, '""')}"`;
          }
          return cell;
        })
        .join(",")
    )
    .join("\n");
  const blob = new Blob(["\ufeff" + csvContent], {
    type: "text/csv;charset=utf-8;",
  });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);
  link.setAttribute("href", url);
  link.setAttribute("download", "参展企业轮播导入模板.csv");
  link.style.visibility = "hidden";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success("模板下载成功");
};

const triggerExhibitorImport = () => {
  exhibitorImportRef.value?.click();
};

const handleExhibitorImport = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("type", "exhibitor");

    const apiConfig = config.getApiConfig();
    const response = await fetch(
      `${apiConfig.baseURL}/admin/homepage/exhibitors/import`,
      {
        method: "POST",
        headers: {
          token: localStorage.getItem("adminToken") || "",
        },
        body: formData,
      }
    );

    const result = await response.json();
    if (result && (result.code === "200" || result.code === 200)) {
      ElMessage.success(
        `批量导入成功，共导入 ${result.data?.successCount || 0} 条数据`
      );
      // 只刷新参展企业数据
      await loadExhibitorsData();
    } else {
      ElMessage.error(result?.message || "批量导入失败");
    }
  } catch (error) {
    console.error("批量导入失败:", error);
    ElMessage.error("批量导入失败");
  } finally {
    // 清空文件选择
    if (exhibitorImportRef.value) {
      exhibitorImportRef.value.value = "";
    }
  }
};

// 展会协助管理
const addAssistance = () => {
  editType.value = "assistance";
  editDialogTitle.value = "添加协助项";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    description: "",
    icon: "",
    link: "",
    sort: assistanceData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editAssistance = (row) => {
  editType.value = "assistance";
  editDialogTitle.value = "编辑协助项";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteAssistance = (index) => {
  assistanceData.value.splice(index, 1);
  ElMessage.success("删除成功");
};

const toggleAssistanceStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 展会图片轮播管理
const addGalleryImage = () => {
  editType.value = "gallery";
  editDialogTitle.value = "添加图片";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    title: "",
    description: "",
    url: "",
    sort: galleryData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editGalleryImage = (row) => {
  editType.value = "gallery";
  editDialogTitle.value = "编辑图片";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteGalleryImage = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这张图片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = galleryData.value[index];
    if (item.id) {
      // 如果有ID，调用API删除
      const response = await homepageApi.deleteContent(item.id);
      if (response && response.code === "200") {
        galleryData.value.splice(index, 1);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败");
      }
    } else {
      // 如果没有ID，直接删除
      galleryData.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除图片失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleGalleryStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 宣传视频管理
const addVideoTag = () => {
  if (newTag.value.trim()) {
    videoData.features.push(newTag.value.trim());
    newTag.value = "";
  }
  showTagInput.value = false;
};

const removeVideoTag = (index) => {
  videoData.features.splice(index, 1);
};

// 展会亮点管理
const addHighlight = () => {
  editType.value = "highlight";
  editDialogTitle.value = "添加亮点";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    icon: "",
    title: "",
    description: "",
    sort: highlightsData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editHighlight = (row) => {
  editType.value = "highlight";
  editDialogTitle.value = "编辑亮点";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteHighlight = (index) => {
  highlightsData.value.splice(index, 1);
  ElMessage.success("删除成功");
};

const toggleHighlightStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 展区介绍管理
const addZone = () => {
  editType.value = "zone";
  editDialogTitle.value = "添加展区";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    name: "",
    description: "",
    image: "",
    features: [],
    sort: zonesData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editZone = (row) => {
  editType.value = "zone";
  editDialogTitle.value = "编辑展区";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deleteZone = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个展区吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = zonesData.value[index];
    if (item.id) {
      // 如果有ID，调用API删除
      const response = await homepageApi.deleteContent(item.id);
      if (response && response.code === "200") {
        zonesData.value.splice(index, 1);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败");
      }
    } else {
      // 如果没有ID，直接删除
      zonesData.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除展区失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const toggleZoneStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 合作伙伴管理
const addPartner = () => {
  editType.value = "partner";
  editDialogTitle.value = "添加合作伙伴";
  // 完全清空editForm，确保新增时没有ID
  Object.keys(editForm).forEach((key) => delete editForm[key]);
  Object.assign(editForm, {
    name: "",
    logo: "",
    website: "",
    sort: partnersData.value.length + 1,
    status: "active",
  });
  editDialogVisible.value = true;
};

const editPartner = (row) => {
  editType.value = "partner";
  editDialogTitle.value = "编辑合作伙伴";
  Object.assign(editForm, { ...row });
  editDialogVisible.value = true;
};

const deletePartner = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除这个合作伙伴吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = partnersData.value[index];
    if (item.id) {
      // 如果有ID，调用API删除
      const response = await homepageApi.deleteContent(item.id);
      if (response && response.code === "200") {
        partnersData.value.splice(index, 1);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败");
      }
    } else {
      // 如果没有ID，直接删除
      partnersData.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除合作伙伴失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const togglePartnerStatus = (row) => {
  row.status = row.status === "active" ? "inactive" : "active";
  ElMessage.success("状态更新成功");
};

// 保存编辑表单
const saveEditForm = async () => {
  try {
    // liveImage：本地数组维护，并同时触发立即持久化保存
    if (editType.value === "liveImage") {
      const payload = {
        id: editForm.id || undefined,
        title: editForm.title || "",
        description: editForm.description || "",
        url: editForm.image || "", // 使用image字段
        link: editForm.link || "",
        sort: editForm.sort || liveData.images.length + 1,
        status: editForm.status || "active",
      };

      if (editForm.__index != null) {
        // 编辑：按索引覆盖
        liveData.images.splice(editForm.__index, 1, payload);
      } else if (editForm.id && editForm.id !== "") {
        // 编辑：按id替换
        const idx = liveData.images.findIndex((i) => i.id === editForm.id);
        if (idx > -1) liveData.images.splice(idx, 1, payload);
        else liveData.images.push(payload);
      } else {
        // 新增
        liveData.images.push(payload);
      }

      // 立即持久化 live 数据
      try {
        const existingLive = await homepageApi.getContentByType("live");
        const liveFormData = {
          contentType: "live",
          title: liveData.title,
          subtitle: liveData.subtitle,
          content: JSON.stringify({
            status: liveData.status,
            viewers: liveData.viewers,
            images: liveData.images.filter((img) => img.status === "active"),
          }),
          sortOrder: 6,
          status: "active",
        };

        if (existingLive && existingLive.data && existingLive.data.length > 0) {
          liveFormData.id = existingLive.data[0].id;
          await homepageApi.updateContent(liveFormData);
        } else {
          await homepageApi.addContent(liveFormData);
        }

        ElMessage.success("直播图片已保存");
      } catch (e) {
        console.error("直播图片保存失败:", e);
        ElMessage.error("直播图片保存失败");
      }

      editDialogVisible.value = false;
      return;
    }

    // 根据editType构建不同的数据结构
    let formData = {
      contentType:
        editType.value === "event"
          ? "events"
          : editType.value === "testimonial"
          ? "testimonials"
          : editType.value,
      title: editForm.title,
      subtitle: editForm.subtitle,
      imageUrl: editForm.image,
      linkUrl: editForm.linkUrl || "",
      sortOrder: editForm.sort || 0,
      status: editForm.status || "active",
    };

    // 根据不同类型构建content字段
    if (editType.value === "event") {
      formData.content = JSON.stringify({
        buttonText: (editForm.buttonText || "").toString().trim(),
        description: editForm.description,
      });
    } else if (editType.value === "testimonial") {
      formData.title = editForm.company;
      formData.content = JSON.stringify({ content: editForm.content });
    } else if (editType.value === "exhibitor") {
      // 参展企业：改为exhibitors类型，并映射字段
      formData = {
        contentType: "exhibitors",
        title: editForm.name,
        imageUrl: editForm.logo,
        content: JSON.stringify({ group: Number(editForm.group || 1) }),
        sortOrder: editForm.sort || 0,
        status: editForm.status || "active",
      };
    } else if (editType.value === "carousel") {
      formData.content = JSON.stringify({
        buttonText: (editForm.buttonText || "").toString().trim(),
        description: editForm.description,
        action: (editForm.action || "").toString().trim(),
        link: (editForm.link || "").toString().trim(),
      });
    } else {
      formData.content = JSON.stringify({
        description: editForm.description,
        buttonText: editForm.buttonText,
        ...editForm,
      });
    }

    if (editForm.id && editForm.id !== "") {
      // 更新现有内容
      formData.id = editForm.id;
      await homepageApi.updateContent(formData);
    } else {
      // 添加新内容（使用新增接口）
      await homepageApi.addContent(formData);
    }

    ElMessage.success("保存成功");
    editDialogVisible.value = false;

    // 重新加载数据
    await loadHomepageContent();
    await loadOtherContent();
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败: " + (error.message || "未知错误"));
  }
};
</script>

<style scoped>
.admin-homepage {
  padding: 20px;
}

/* 确保表格正常显示 */
.admin-homepage :deep(.el-table) {
  position: relative;
  z-index: 1;
}

/* 图片预览弹窗样式 */
.image-preview-dialog :deep(.el-dialog) {
  z-index: 2000 !important;
}

.image-preview-dialog :deep(.el-overlay) {
  z-index: 1999 !important;
}

.image-preview-content {
  text-align: center;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 50vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content-tabs {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tab-content {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.stat-item .el-input {
  flex: 1;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stat-header h4 {
  margin: 0;
  color: #333;
}

.stat-actions {
  display: flex;
  gap: 8px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-card .el-form-item {
  margin-bottom: 15px;
}

.add-stat-button {
  text-align: center;
  margin-top: 20px;
}

/* 查询表单样式 */
.query-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.query-form .el-form-item {
  margin-bottom: 15px;
}

.query-form .el-button {
  margin-left: 10px;
}

/* 图片上传样式 */
.image-upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  display: block;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}

/* 视频上传样式 */
.video-upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.video-uploader {
  display: inline-block;
}

.video-preview {
  margin-top: 10px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .section-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .action-buttons {
    flex-direction: column;
    gap: 3px;
  }

  .action-buttons .el-button {
    width: 100%;
  }

  .image-uploader-icon,
  .uploaded-image {
    width: 120px;
    height: 120px;
    line-height: 120px;
  }
}
</style>
